package com.example.binarytree;

import com.example.structure.TreeNode;

/**
 * 617. 合并二叉树
 * 给定两个二叉树，想象当你将它们中的一个覆盖到另一个上时，两个二叉树的一些节点便会重叠。
 * <p>
 * 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠，那么将他们的值相加作为节点合并后的新值，否则不为 NULL 的节点将直接作为新二叉树的节点。
 * <p>
 * 示例 1:
 * <p>
 * 输入:
 * Tree 1                     Tree 2
 * 1                         2
 * / \                       / \
 * 3   2                     1   3
 * /                           \   \
 * 5                             4   7
 * 输出:
 * 合并后的树:
 * 3
 * / \
 * 4   5
 * / \   \
 * 5   4   7
 */
public class MergeTwoBinaryTrees {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) {
            return root2;
        }
        if (root2 == null) {
            return root1;
        }
        TreeNode root = new TreeNode(root1.val + root2.val);
        root.left = mergeTrees(root1.left, root2.left);
        root.right = mergeTrees(root1.right, root2.right);
        return root;
    }
}


class Solution {
    public static boolean isValidBST(TreeNode root) {
        return isValidBST(root, root, root.left, root.right);
    }

    public static boolean isValidBST(TreeNode pre, TreeNode root, TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        else if (left == null && root.val < right.val && right.val > pre.val)
            return isValidBST(root, right, right.left, right.right);
        else if (right == null && root.val > left.val && left.val < pre.val)
            return isValidBST(root, left, left.left, left.right);
        else if (left != null && right != null && root.val < right.val && root.val > left.val && right.val > pre.val && left.val < pre.val)
            return isValidBST(root, right, right.left, right.right) && isValidBST(root, left, left.left, left.right);
        return false;
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(1);
        //   ConstructMaximumBinaryTree.constructMaximumBinaryTree(new int[]{5,4,6,null,null,3,7});
        Solution.isValidBST(node);
    }
}